package com.woniuxy.email.config;

import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author yellow Docter
 * @date 2024-10-24
 * @desc 蜗牛创想：www.woniuxy.com
 */
@Configuration
public class RabbitConfig {

    //把 消息确认 在 模板类中进行配置
    /**
     * 修改RabbitTemplate对象的配置
     *
     *   RabbitTemplate 创建对象 添加到IOC容器中
     *       Redis的连接工厂  ConnectionFactory (自动装配创建的)
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        // 开启消息强制投递
        rabbitTemplate.setMandatory(true);
        // 消息到达交换机的确认回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println("消息数据：" + correlationData);
            if (ack) {
                System.out.println("消息已到达交换机");
            } else {
                System.out.println("消息未到达交换机，原因是：" + cause);
            }
        });

        //消息从交换机到 队列失败的回调 (发送到队列失败 回到交换机 )
        rabbitTemplate.setReturnsCallback(returned -> {
            System.out.println("消息对象 = " + returned.getMessage());
            System.out.println("错误码 = " + returned.getReplyCode());
            System.out.println("错误原因= " + returned.getReplyText());
            System.out.println("交换机 = " + returned.getExchange());
            System.out.println("路由key = " + returned.getRoutingKey());
        });

        return rabbitTemplate;
    }

}
